package com.easyj.admin.edu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import com.easyj.base.common.export.ExpExcutor;
import com.easyj.base.common.export.ExpField;
import com.easyj.base.util.DateTimeUtil;
import com.easyj.base.common.page.PageFilter;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.ValidateException;
import com.easyj.base.common.page.Page;
import com.easyj.admin.activiti.vo.SimpleApproveVO;
import com.easyj.admin.db.model.Publish;
import com.easyj.admin.db.model.PublishQO;
import com.easyj.admin.edu.service.PublishService;
	/**
	* 教师发表
	*
	 */
	@RestController
	@RequestMapping(value = "/edu/publish")
	public class PublishController extends BaseController{

		@Autowired
		private  PublishService publishService;

		/**
		 * get
		 * @param id
		 * @return
		 */
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	        Publish entity = publishService.findById(id);
	        return Result.Success(entity);
	    }
		
		/**
		* 新增申请
		*/
		@PreAuthorize("hasPermission('publish','publish:apply')")
		@PostMapping(value = "apply")
		public Result apply(@RequestBody @Validated Publish entity,BindingResult validResult) {
			try{
                if(validResult.hasErrors()) {
					throw new ValidateException("数据不符合要求！");
				} 			
				publishService.apply(entity);
				return Result.Success();
			}catch(EasyjException ex){
				return Result.Error(ex.getCode(),ex.getMessage()); 
			}catch(Exception ex){
			   log.error("PublishController.apply", ex);
			   return Result.Error("提交申请错误！"+ex.getMessage()); 
			}
		}
		

	    @RequestMapping(value = "findCommentsById", method = RequestMethod.GET)
		public Result findCommentsById(@RequestParam(value = "id") Long id) {
			return Result.Success(publishService.findCommentsById(id));
			
		}
		
		/**
		* 查询自己的申请
		* @param filter
		* @return
		*/

		@PostMapping(value = "findSelf")
		public Result findSelf(@RequestBody  PublishQO filter) {
			try{
			    if(filter.getPage().getLimit()>MaxLimit) {
					return Result.Error(10009,"超出一次读取最大行数"); 
				}
			   //set applicantId
			    filter.setApplicantId(this.getUserId());
				Page<Publish>  page =publishService.findPage(filter);
				return Result.Success(page);
			}catch(Exception ex){
			    log.error("PublishController.findSelf", ex);
				return Result.Error("查询教师发表错误！");   
			}
		}
		
		/**
	    *提交后不可修改 
		* 修改自己的申请
		@PutMapping
		public Result update(@RequestBody @Validated Publish entity,BindingResult validResult) {
			try{
                if(validResult.hasErrors()) {
					throw new ValidateException("数据不符合要求！");
				}  			
				publishService.updateEntity(entity);
				return Result.Success();
			}catch(EasyjException ex){
				return Result.Error(ex.getCode(),ex.getMessage()); 
			}catch(Exception ex){
			   log.error("PublishController.update", ex);
			   return Result.Error("修改错误！"+ex.getMessage()); 
			}
		}
        */
		
		/**
		  * 审核
       * @throws EasyjException 
		 */
		@PostMapping(value = "auditApply")
		public Result auditApply(@RequestBody SimpleApproveVO approve,BindingResult validResult) throws EasyjException {
          if(StringUtils.isBlank(approve.getComment())) {
				throw new ValidateException("请输入处理意见！");
		  } 
          
          approve.setApproveUserId(this.getUserId());          
          publishService.auditApply(approve);
			return Result.Success();
			
		}
		
		
			
 		 /**
 		 *取消自己的申请
         * @throws EasyjException 
 		*/
		@RequestMapping(value = "cancel", method = RequestMethod.GET)
 		public Result cancel(@RequestParam(value = "id") Long id) throws EasyjException{
			publishService.cancel(id);
 			return Result.Success();
 			
 		}	
		
        /**
		  * 审批
		 */
		@PostMapping(value = "approve")
		public Result approve(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) {
			try{
                if(validResult.hasErrors()) {
					throw new ValidateException("数据不符合要求！");
				} 
                entity.setApproveUserId(this.getUserId());
                
				publishService.approve(entity);
				return Result.Success();
			}catch(EasyjException ex){
				return Result.Error(ex.getCode(),ex.getMessage()); 
			}catch(Exception ex){
			   log.error("PublishController.approve", ex);
			   return Result.Error("提交审批错误！"+ex.getMessage()); 
			}
		}
 		
 		/**
		* 分页查询
		* @param filter
		* @return
		 */
		@PreAuthorize("hasPermission('publish','publish:list')")
		@PostMapping(value = "findPage")
		public Result findPage(@RequestBody  PublishQO filter) {
			try{
			    if(filter.getPage().getLimit()>MaxLimit) {
					return Result.Error(10009,"超出一次读取最大行数"); 
				}
				Page<Publish>  page =publishService.findPage(filter);
				return Result.Success(page);
			}catch(Exception ex){
			    log.error("PublishController.findPage", ex);
				return Result.Error("查询教师发表错误！");   
			}
		}
		

      /**
		* 导出Excel
		* @param filter
		* @param expFields
		* @param response
		*/
		@PreAuthorize("hasPermission('publish','publish:list;publish:approve')")
		@RequestMapping(value = "export", method = RequestMethod.POST)
		public void export(@RequestBody PublishQO filter, HttpServletResponse response){
			try {
				 //导出的字段		
				List<ExpField> fields = new ArrayList<ExpField>();
				fields.add(new ExpField("applyName","申请标题",""));
			      fields.add(new ExpField("applicantName","申请人",""));
			      fields.add(new ExpField("deptName","所属部门",""));
			      fields.add(new ExpField("applyTime","申请日期","","date"));
			      fields.add(new ExpField("name","成果名称",""));
			      fields.add(new ExpField("typeName","成果形式",""));
			      fields.add(new ExpField("content","成果描述",""));
			      fields.add(new ExpField("role","承担角色",""));
			      fields.add(new ExpField("firstAuthor","第一作者",""));
			      fields.add(new ExpField("firsAuthorOrg","第一作者所属单位",""));
			      fields.add(new ExpField("publishName","刊物名称",""));
			      fields.add(new ExpField("publishLevelName","刊物级别",""));
			      fields.add(new ExpField("publishNo","期刊号/书号",""));
			      fields.add(new ExpField("press","出版单位",""));
			      fields.add(new ExpField("pressDate","发表日期","","date"));
			      fields.add(new ExpField("approveName","审核人",""));
			      fields.add(new ExpField("approveTime","审核日期","","date"));
			      fields.add(new ExpField("auditComment","审核意见",""));
			      fields.add(new ExpField("statusName","状态",""));
			    
				//生成 excel
				SXSSFWorkbook workbook=exportExcel(filter, fields);
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="教师发表"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			} catch (Exception ex) {
				log.error("PublishController.export", ex);
			} 
		}
		
		/**
		* 导出excel,生成workbook 
		*/
		private SXSSFWorkbook exportExcel(final PublishQO filter,List<ExpField> fields) {
			ExpExcutor<Publish>  expExcutor=new ExpExcutor<Publish>(){
				@Override
				protected Long getRecordCount() {
					return publishService.count(filter);
				}

				@Override
				protected List<Publish> getSheetData(int sheetSize, int sheetinx) {
					PageFilter queryPage=new PageFilter(sheetSize,sheetinx+1);
					filter.setPage(queryPage);
					List<Publish> datas= publishService.findList(filter);
					
				
					return datas;
				}
			};
			SXSSFWorkbook workbook=expExcutor.export(fields,false);
			return workbook;
		}	
		
}

